import Vue from 'vue'
import store from '@/store'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login')
  },
  {
    path: '/',
    component: () => import('@/views/home'),
    children: [
      {
        path: '',
        name: 'welcome',
        component: () => import('@/views/welcome')
      },
      {
        path: '/companys',
        name: 'companys',
        component: () => import('@/views/companys-adm')
      },
      {
        path: '/interview',
        name: 'interview',
        component: () => import('@/views/Interview-skills')
      },
      {
        path: '/userlist',
        name: 'userlist',
        component: () => import('@/views/user/UserList.vue')
      },
      {
        path: '/userrights',
        name: 'userrights',
        component: () => import('@/views/user/UserRights.vue')
      }, {
        path: '/audit',
        name: 'audit',
        component: () => import('@/views/basemanagement/audit')
      }, {
        path: '/basics',
        name: 'basics',
        component: () => import('@/views/basemanagement/basics')
      }, {
        path: '/choiceness',
        name: 'choiceness',
        component: () => import('@/views/basemanagement/choiceness')
      }, {
        path: '/itemlist',
        name: 'itemlist',
        component: () => import('@/views/basemanagement/itemlist')
      }, {
        path: '/preview',
        name: 'preview',
        component: () => import('@/views/basemanagement/preview')
      }, {
        path: '/subject',
        name: 'manage',
        component: () => import('@/views/subjectManage')
      },
      {
        path: '/entry',
        name: 'entry',
        component: () => import('@/views/basemanagement/entry')
      },
      {
        path: '/subject/sort',
        name: 'subjectSort',
        component: () => import('@/views/subjectManage/subjectSort')
      },
      {
        path: '/subject/tag',
        name: 'subjectTag',
        component: () => import('@/views/subjectManage/subjectSort'),
        props: true
      }
    ]
  },
  { path: '*', redirect: '/' }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const { state } = store
  if (!window.localStorage.getItem('HMMM_TOKEN') && to.path !== '/login') {
    next({
      path: '/login'
    })
  }
  // find path
  const { pageList } = state
  const i = pageList.findIndex(item => {
    return item.path === to.path
  })
  if (i < 0) {
    store.commit('pushPageList', {
      path: to.path,
      tagName: to.name
    })
    store.commit('setPageIdx', pageList.length - 1)
  } else {
    store.commit('setPageIdx', i)
  }
  next()
})

export default router
